package com.postracker.postracker.db.action.load;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import com.postracker.postracker.db.action.DbStatements;
import com.postracker.postracker.io.Table;
import com.postracker.postracker.io.TableList;

class TablesWithData implements DbStatements {

	private TableList tableList;
	private TableRow row;

	protected TablesWithData(TableList tableList, TableRow row) {
		this.tableList = tableList;
		this.row = row;
	}

	@Override
	public List<String> getStatements() {
		return getStmtsFromAllTables();
	}

	private List<String> getStmtsFromAllTables() {
		List<String> statements = new ArrayList<String>();
		for (Table table : tableList.getTables()) {
			statements.addAll(getAllStmts(table));
		}
		return statements;
	}

	private List<String> getAllStmts(Table table) {
		List<String[]> allRows = table.getRows();
		if (allRows.isEmpty()) {
			return Collections.<String> emptyList();
		}
		Iterator<String[]> iterator = allRows.iterator();
		String[] sortedColumns = allRows.get(0);
		row.setTableName(table.getTableName());
		row.setSortedColumns(sortedColumns);
		List<String> statements = new ArrayList<String>();
		while (iterator.hasNext()) {
			row.setSortedValues(iterator.next());
			statements.addAll(row.getStatements());
		}
		return statements;
	}

}
